/**
 * for product
 */
$(function(){
	getProductLists(1);
	// Check all checkboxes when the one in a table head is checked:			
	$('.check-all').click(function(){
		$("#datatable tbody tr").find("input[type='checkbox']").attr('checked', $(this).is(':checked'));   
	});
	
	$(".form-layout .button").click(function(){
		//var dataArray = $("form").serializeArray();		
		getProductLists(1, null, null, getParamer());
	})

	$(".batchOp").click(function(){
		if($("#batchOp").val() == ""){
			showInfo("請選擇操作類型.");
		}else{
			var array = [];
			var isSaveLanguageId = true;
			var dataLanguages = [];
			$("[name='productId']:checked").each(function(i){
				array[i] = $(this).val();
				var dataLanguage = $(this).parents("tr").find("td[data-language]").attr("data-language");
				if(dataLanguages.length > 0 && $.inArray(dataLanguage, dataLanguages) == -1){
					isSaveLanguageId = false;
				}
				dataLanguages[i] = dataLanguage;				
			})
			if(array.length > 0){
				if($("#batchOp").val() == 'Delete'){
					showMessage({message:"你確定執行刪除操作嗎?"},{OK:function(){
						$.ajax({
							url: ctx+"/product/delete.do",
							type: "post",
							data : {productIds : $.toJSON(array)},
							success: function(){
								getProductLists(1, null, null, getParamer());
							}
						})
						$(".check-all").attr("checked", false);			
					}, Cancel:function(){}});
				}else if($("#batchOp").val() == 'moveCategory'){
					if(!isSaveLanguageId){
						showInfo("請選擇相同語言的產品！");
						return false;
					}
					var language = $("#choose_languageId").children("option[value='"+dataLanguages+"']").attr("data-key");
					if(language == 'zh' ){
						$(".zh_chooseCategory").show();
						$(".en_chooseCategory").hide();
					}else{
						$(".zh_chooseCategory").hide();		
						$(".en_chooseCategory").show();
					}
					$("#choose_languageId").parent("p").hide();
					var chooseCategory = $("#chooseCategory");
					showMessage({object:chooseCategory,title:"選擇類別",width:400,height:250},{OK:function(){
						var categoryId = $("#choose_productCategoryId").val();
						$.ajax({
							url: ctx+"/product/changeCategory.do",
							type: "post",
							data : {productIds : $.toJSON(array),categoryId:categoryId},
							success: function(){
								getProductLists(1, null, null, getParamer());
							}
						})
						$(".check-all").attr("checked", false);							
					},Cancel:function(){}});
				}
			}else{
				showInfo("請選擇產品.");
			}
		}
	})
	$(".sort").click(function(){
		var orderBy = $(this).attr("title");
		var orderType = "asc";
		if($(this).hasClass("asc")){
			orderType = "desc";
			$(this).addClass("desc").removeClass("asc");
		}else{
			$(this).addClass("asc").removeClass("desc");
		}
		getProductLists(1, orderType, orderBy, getParamer());
	})
	$("#add").click(function(){
		location.href=ctx+"/product/add.do";
	})

	$("#choose_languageId").on("change", function(){
		var language = $(this).children("option:selected").attr("data-key");
		if(language == 'zh' ){
			$(".zh_chooseCategory").show();
			$(".en_chooseCategory").hide();
		}else{
			$(".zh_chooseCategory").hide();		
			$(".en_chooseCategory").show();
		}
	})
})
function getParamer(){
	var data = [];
	var productName = {};
	productName["property"] = "productName";
	productName["value"] = $("#productName").val();
	productName["condition"] = "fl";
	if(isNotBlank($("#productName").val())){
		data[0] = productName;
	}
	var productModel = {};
	productModel["property"] = "productModel";
	productModel["value"] = $("#productModel").val();
	productModel["condition"] = "fl";
	if(isNotBlank($("#productModel").val())){
		data[data.length] = productModel;
	}
	var productStatus = {};	
	productStatus["property"] = "productStatus";
	productStatus["value"] = $("#productStatus").val();	
	productStatus["condition"] = "eq";
	if(isNotBlank($("#productStatus").val())){
			data[data.length] = productStatus;		
	}
	
	var languageId = {};
	languageId["property"] = "l.languageId";
	languageId["value"] = $("#languageId").val();
	languageId["condition"] = "eq";
	if(isNotBlank($("#languageId").val())){
		data[data.length] = languageId;
	}
	
	return $.toJSON(data);
}
function getProductLists(pageNo, orderType, orderBy, paramdata){	
			if(!pageNo){
				pageNo = 1;
			}
			if(!orderType){
				orderType = "desc";
			}
			if(!orderBy){
				orderBy = "isTop";
			}
			if(!paramdata){
				paramdata="[]";
			}
			pagination({
				url:ctx+"/product/search.do",
				data:{
					pageNo:pageNo, 
					orderType : orderType, 
					orderBy : orderBy, 
					rules : paramdata
				},
				callback: function(data){
					generateProductLists(data);
					paginationClick();
				}
			})
		}

		function generateProductLists(data){
			$("#datatable tbody").empty();
			if(data.result){
				$.each(data.result, function(index, rowdata){						
					var edit = $('<a href="javascript:void(0)" title="Edit">編輯</a>');
					var hotText = "熱圖";
					if(isNotBlank(rowdata.linkedHeatMapId) && rowdata.linkedHeatMapStatus)
						hotText = "取消熱圖";
					var hot = $('<a href="javascript:void(0)" title="Hot"></a>').text(hotText).data("uploadFileSetInfoId", rowdata.uploadFileSetInfoId);
					var top = $('<a href="javascript:void(0)" title="Top"></a>').text(rowdata.isTop?"取消置頂":"置頂");
					var publish = $('<a href="javascript:void(0)" title="Publish"></a>').text(rowdata.productStatus?"取消發佈":"發佈");
					var tr = $("<tr>")
					.append($("<td>").append($("<input type='checkbox'>").attr("name", "productId").val(rowdata.productId)).addClass("text-center"))
					.append($("<td>").text(rowdata.productNo).attr("data-no", rowdata.productNo))
					.append($("<td>").text(rowdata.productModel))
					.append($("<td>").text(rowdata.productName))
					.append($("<td>").text(rowdata.categoryName))
					.append($("<td>").text(rowdata.productStatus?"已發佈":"未發佈"))
					.append($("<td>").text(rowdata.productDate))
					.append($("<td>").text(rowdata.languageName).attr("data-language", rowdata.languageId))
					//.append($("<td>").text(rowdata.modifiedOn))
					.append($("<td>").append(edit).addClass("text-center op-1"))
					.append($("<td>").append(hot).addClass("text-center op-2").attr("data-hot", rowdata.linkedHeatMapStatus?true:false))
					.append($("<td>").append(top).addClass("text-center op-3").attr("data-top", rowdata.isTop))
					.append($("<td>").append(publish).addClass("text-center op-4").attr("data-status", rowdata.productStatus));
					$("#datatable tbody").append(tr);
				})
				operation();
			}
		    // Alternating table rows:					
			$('#datatable tbody tr:even').addClass("alt-row"); // Add class "alt-row" to even table rows
		}
        
		function operation(){
			$("#datatable tbody tr").each(function(){
				var ele = this;
				var productId = $(this).find(":checkbox").val();
				$(this).find("a").on("click", function(){
					var title = $(this).attr("title");
					if('Edit'.equals(title)){
						var productNo = $(ele).find("td[data-no]").attr("data-no");
						var productLanguage = $(ele).find("td[data-language]").attr("data-language");
						location.href=ctx+"/product/edit/"+productNo+".do?languageId="+productLanguage;
					}else if("Delete".equals(title)){
						$.ajax({
							url: ctx+"/product/delete/"+productId+".do",
							type: "post",
							success: function(){
								getProductLists(1);
							}
						})
					}else if("Hot".equals(title)){
						var isHot = $(ele).find("td[data-hot]").attr("data-hot");
						var uploadFileSetInfoId = $(this).data("uploadFileSetInfoId");
						if(uploadFileSetInfoId){
							if(isHot == 'true'){
								showMessage({message:"Are you sure perform the operation!"},{
								OK:function(){
									$.ajax({
										url: ctx+"/home/heatMap/"+productId+".do",
										type: "post",
										data : {type : 1, isHot:isHot },
										success: function(){
											getProductLists(1);
										}
									})							
								},Cancel: function(){}
								})
							}else{
								$.ajax({
									url: ctx+"/home/heatMap/"+productId+".do",
									type: "post",
									data : {type : 1, isHot:isHot },
									success: function(){
										getProductLists(1);
									}
								})
							}
						}else{
							showInfo("This prodct does not has any picture!")
						}
					}else if("Top".equals(title)){
						var isTop = $(ele).find("td[data-top]").attr("data-top");
						$.ajax({
							url: ctx+"/product/top/"+productId+".do",
							type: "post",
							data : {isTop : isTop},
							success: function(){
								getProductLists(1);
							}
						})
					}else if("Publish".equals(title)){
						var productStatus = $(ele).find("td[data-status]").attr("data-status");
						$.ajax({
							url: ctx+"/product/publish/"+productId+".do",
							type: "post",
							data : {productStatus : productStatus},
							success: function(){
								getProductLists(1);
							}
						})
					}				
				})
			})
		}
       function paginationClick(){
    	   $(".pagination a:not(.disabled):not(.info):not(.current)").on("click",function(){
    		   var pageNo = $(this).attr("data-page");
    		   getProductLists(pageNo);
    	   })
       }       